import { ScrollView, StyleSheet, View, Dimensions, ActivityIndicator, TouchableOpacity, SafeAreaView, FlatList, Image, Platform, StatusBar, Alert, RefreshControl } from 'react-native';
import { useState, useRef, useEffect, useMemo, useCallback } from 'react';
import { Tab, TabView } from '@rneui/themed';
import { ThemedText } from '@/components/ThemedText';
import { getDishsByCategory, fetchDishes } from '@/data/dishes';
import DishCard from '@/components/DishCard';
import { LinearGradient } from 'expo-linear-gradient';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { FontAwesome } from '@expo/vector-icons';
import FloatingHeart from '@/components/FloatingHeart';
import CartDrawer from '@/components/CartDrawer';
import CustomAlert from '@/components/CustomAlert';
import Toast from '@/components/Toast';
import AddDishModal from '@/components/AddDishModal';

const windowWidth = Dimensions.get('window').width;

const categories = [
  { id: 'all', name: '全部' },
  { id: 'meat', name: '荤菜' },
  { id: 'vegetable', name: '素菜' },
  { id: 'dessert', name: '甜食' },
];

// 主组件
export default function MenuScreen() {
  const [index, setIndex] = useState(0);
  const [likedDishes, setLikedDishes] = useState<string[]>([]);
  const [confirmedDishes, setConfirmedDishes] = useState<string[]>([]);
  const [todayDishes, setTodayDishes] = useState<Dish[]>([]);
  const [floatingHearts, setFloatingHearts] = useState<Array<{
    id: string;
    startX: number;
    startY: number;
    endX: number;
    endY: number;
  }>>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);
  const [isCartOpen, setIsCartOpen] = useState(false);
  const [isConfirming, setIsConfirming] = useState(false);
  const cartRef = useRef<View>(null);
  const mountedRef = useRef(true);
  const [isLoadingToday, setIsLoadingToday] = useState(true);
  const [alertConfig, setAlertConfig] = useState<{
    visible: boolean;
    message: string;
    type: 'success' | 'error';
  }>({
    visible: false,
    message: '',
    type: 'success'
  });
  const [toastConfig, setToastConfig] = useState<{
    visible: boolean;
    message: string;
    type: 'success' | 'error';
  }>({
    visible: false,
    message: '',
    type: 'success'
  });
  const [isAddDishModalVisible, setIsAddDishModalVisible] = useState(false);
  const [refreshing, setRefreshing] = useState(false);

  const handleLikeDish = useCallback((dishId: string, startX: number, startY: number) => {
    // 检查当前状态
    const isCurrentlyLiked = likedDishes.includes(dishId);
    
    // 如果是取消喜欢，直接更新状态
    if (isCurrentlyLiked) {
      setLikedDishes(prev => prev.filter(id => id !== dishId));
      return;
    }

    // 如果是添加喜欢，并且有有效的点击坐标
    if (startX > 0 && startY > 0 && cartRef.current) {
      cartRef.current.measure((x, y, width, height, pageX, pageY) => {
        if (typeof pageX === 'number' && typeof pageY === 'number') {
          // 考虑SafeAreaView的偏移
          const safeAreaOffset = Platform.OS === 'ios' ? 47 : 0; // iOS状态栏高度大约是47
          const endX = pageX + width / 2;
          const endY = pageY + height / 2 - safeAreaOffset;
          
          // 添加新的浮动爱心
          setFloatingHearts(prev => [
            ...prev,
            {
              id: `${dishId}-${Date.now()}`,
              startX,
              startY: startY - safeAreaOffset,
              endX,
              endY,
            },
          ]);
          
          // 更新喜欢状态
          setLikedDishes(prev => [...prev, dishId]);
        }
      });
    } else {
      // 如果没有有效坐标或购物车引用，直接更新状态
      setLikedDishes(prev => [...prev, dishId]);
    }
  }, [likedDishes]);

  const removeFloatingHeart = (heartId: string) => {
    setFloatingHearts(prev => prev.filter(heart => heart.id !== heartId));
  };

  const handleRemoveDish = (dishId: string) => {
    setLikedDishes(prev => prev.filter(id => id !== dishId));
  };

  // 缓存喜欢的菜品数据
  const likedDishesData = useMemo(() => {
    const processedIds = new Set<string>();
    return categories.flatMap(category => 
      getDishsByCategory(category.id)
        .filter(dish => {
          if (likedDishes.includes(dish.id) && !processedIds.has(dish.id)) {
            processedIds.add(dish.id);
            return true;
          }
          return false;
        })
    );
  }, [likedDishes]);

  const handleConfirmDishes = async () => {
    try {
      setIsConfirming(true);
      const response = await fetch('http://116.205.137.46/api/today-dishes', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          dishIds: likedDishes
        })
      });

      if (!response.ok) {
        throw new Error('确认选菜失败');
      }

      // 更新确认的菜品
      setConfirmedDishes(likedDishes);
      // 清空喜欢的菜品列表
      setLikedDishes([]);
      // 重新获取今日菜品
      await fetchTodayDishes();
      // 关闭购物车抽屉
      setIsCartOpen(false);
      // 显示成功提示
      setAlertConfig({
        visible: true,
        message: '选菜成功！今日菜品已更新',
        type: 'success'
      });
    } catch (error) {
      console.error('Error confirming dishes:', error);
      setAlertConfig({
        visible: true,
        message: '确认选菜失败，请重试',
        type: 'error'
      });
    } finally {
      setIsConfirming(false);
    }
  };

  // 缓存已确认的菜品数据
  const confirmedDishesData = useMemo(() => {
    const processedIds = new Set<string>();
    return categories.flatMap(category => 
      getDishsByCategory(category.id)
        .filter(dish => {
          if (confirmedDishes.includes(dish.id) && !processedIds.has(dish.id)) {
            processedIds.add(dish.id);
            return true;
          }
          return false;
        })
    );
  }, [confirmedDishes]);

  // 获取今日菜品
  const fetchTodayDishes = async () => {
    try {
      const response = await fetch('http://116.205.137.46/api/today-dishes');
      const data = await response.json();
      const dishes = data.map((dish: any) => ({
        ...dish,
        image: { uri: `http://116.205.137.46${dish.image}` }
      }));
      setTodayDishes(dishes);
      
      // 如果有今日菜品，将其ID添加到想吃清单中
      if (dishes.length > 0) {
        const todayDishIds = dishes.map((dish: any) => dish.id);
        setLikedDishes(prev => {
          // 合并现有的喜欢列表和今日菜品ID，去重
          const combined = [...new Set([...prev, ...todayDishIds])];
          return combined;
        });
      }
    } catch (error) {
      console.error('Error fetching today dishes:', error);
    } finally {
      setIsLoadingToday(false);
    }
  };

  // 删除今日菜品
  const handleDeleteTodayDish = async (dishId: string) => {
    try {
      // 从当前列表中过滤出其他菜品
      const updatedDishes = todayDishes.filter(dish => dish.id !== dishId);
      const updatedDishIds = updatedDishes.map(dish => dish.id);
      
      // 发送更新请求
      const response = await fetch('http://116.205.137.46/api/today-dishes', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          dishIds: updatedDishIds
        })
      });

      if (!response.ok) {
        throw new Error('删除菜品失败');
      }

      // 更新本地状态
      setTodayDishes(updatedDishes);
      // 从喜欢列表中也移除该菜品
      setLikedDishes(prev => prev.filter(id => id !== dishId));

      setToastConfig({
        visible: true,
        message: '删除菜品成功',
        type: 'success'
      });
    } catch (error) {
      console.error('Error deleting dish:', error);
      setToastConfig({
        visible: true,
        message: '删除菜品失败，请重试',
        type: 'error'
      });
    }
  };

  const handleAddDishSuccess = () => {
    // 重新加载菜品列表
    fetchDishes();
  };

  // 初始化加载
  useEffect(() => {
    const loadInitialData = async () => {
      try {
        setIsLoading(true);
        await Promise.all([
          fetchDishes(),
          fetchTodayDishes()
        ]);
        if (mountedRef.current) {
          setIsLoading(false);
        }
      } catch (err) {
        console.error('Error loading data:', err);
        if (mountedRef.current) {
          setError(err instanceof Error ? err : new Error('Unknown error'));
          setIsLoading(false);
        }
      }
    };

    loadInitialData();

    return () => {
      mountedRef.current = false;
    };
  }, []);

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    try {
      await Promise.all([
        fetchDishes(),
        fetchTodayDishes()
      ]);
    } catch (error) {
      console.error('Error refreshing data:', error);
      setToastConfig({
        visible: true,
        message: '刷新失败，请重试',
        type: 'error'
      });
    } finally {
      setRefreshing(false);
    }
  }, []);

  if (error) {
    return (
      <View style={styles.loadingContainer}>
        <ThemedText style={styles.errorText}>
          加载失败: {error.message}
        </ThemedText>
      </View>
    );
  }

  if (isLoading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#ff4d4f" />
      </View>
    );
  }

  return (
    <SafeAreaView style={styles.safeArea}>
      <StatusBar 
        barStyle="light-content"
        backgroundColor="#FF9F45"
        translucent
      />
      <LinearGradient
        colors={['#FF9F45', '#FFC288']}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 1 }}
        style={styles.gradient}
      >
        <GestureHandlerRootView style={{ flex: 1 }}>
          <View style={styles.container}>
            <View style={styles.mainContent}>
              {/* 今日菜品区域 */}
              <View style={styles.todayDishes}>
                <View style={styles.todayHeader}>
                  <ThemedText style={styles.todayTitle}>今日菜品</ThemedText>
                  <TouchableOpacity
                    style={styles.addButton}
                    onPress={() => setIsAddDishModalVisible(true)}
                  >
                    <LinearGradient
                      colors={['#FF9F45', '#FFC288'] as const}
                      start={{ x: 0, y: 0 }}
                      end={{ x: 1, y: 0 }}
                      style={styles.addButtonGradient}
                    >
                      <FontAwesome name="plus" size={16} color="#fff" />
                      <ThemedText style={styles.addButtonText}>添加菜品</ThemedText>
                    </LinearGradient>
                  </TouchableOpacity>
                </View>
                {isLoadingToday ? (
                  <View style={styles.emptyContainer}>
                    <ActivityIndicator size="large" color="#FF9F45" />
                  </View>
                ) : todayDishes.length === 0 ? (
                  <View style={styles.emptyContainer}>
                    <FontAwesome name="cutlery" size={32} color="#FF9F45" />
                    <ThemedText style={styles.emptyText}>
                      暂无今日菜品
                    </ThemedText>
                  </View>
                ) : (
                  <ScrollView 
                    horizontal 
                    showsHorizontalScrollIndicator={false}
                    style={styles.todayScroll}
                  >
                    {todayDishes.map((dish) => (
                      <View key={dish.id} style={styles.todayDishItem}>
                        <Image 
                          source={dish.image} 
                          style={styles.todayDishImage} 
                        />
                        <TouchableOpacity 
                          style={styles.deleteTodayDish}
                          onPress={() => handleDeleteTodayDish(dish.id)}
                        >
                          <View style={styles.deleteIconContainer}>
                            <FontAwesome name="times-circle" size={22} color="#FF9F45" />
                          </View>
                        </TouchableOpacity>
                        <LinearGradient
                          colors={['transparent', 'rgba(0,0,0,0.7)']}
                          style={styles.todayDishGradient}
                        >
                          <ThemedText style={styles.todayDishName}>{dish.name}</ThemedText>
                        </LinearGradient>
                      </View>
                    ))}
                  </ScrollView>
                )}
              </View>

              <View style={styles.tabContainer}>
                <Tab
                  value={index}
                  onChange={setIndex}
                  indicatorStyle={styles.indicator}
                  containerStyle={styles.tabBar}
                >
                  {categories.map((category) => (
                    <Tab.Item
                      key={category.id}
                      title={category.name}
                      titleStyle={(active) => ({
                        color: active ? '#FF9F45' : '#666',
                        fontSize: 15,
                        fontWeight: active ? '600' : '500',
                      })}
                    />
                  ))}
                </Tab>
              </View>

              <TabView
                value={index}
                onChange={setIndex}
                animationType="spring"
              >
                {categories.map((category) => (
                  <TabView.Item 
                    key={category.id}
                    style={styles.tabContent}
                  >
                    <ScrollView 
                      style={styles.content}
                      refreshControl={
                        <RefreshControl
                          refreshing={refreshing}
                          onRefresh={onRefresh}
                          colors={['#FF9F45']}
                          tintColor="#FF9F45"
                          title="正在刷新..."
                          titleColor="#FF9F45"
                        />
                      }
                    >
                      <View style={styles.dishesContainer}>
                        {getDishsByCategory(category.id).map((dish) => (
                          <DishCard 
                            key={dish.id} 
                            dish={dish}
                            onLike={(id, x, y) => handleLikeDish(id, x, y)}
                            isLiked={likedDishes.includes(dish.id)}
                          />
                        ))}
                      </View>
                    </ScrollView>
                  </TabView.Item>
                ))}
              </TabView>
            </View>

            {/* 浮动爱心 */}
            {floatingHearts.map(heart => (
              <FloatingHeart
                key={heart.id}
                startX={heart.startX}
                startY={heart.startY}
                endX={heart.endX}
                endY={heart.endY}
                onComplete={() => removeFloatingHeart(heart.id)}
              />
            ))}

            {/* 购物车图标 */}
            <TouchableOpacity 
              ref={cartRef}
              style={[
                styles.floatingCart,
                { opacity: likedDishes.length > 0 ? 1 : 0.5 }
              ]}
              onPress={() => setIsCartOpen(true)}
            >
              <LinearGradient
                colors={['#FF9F45', '#FFC288']}
                style={styles.cartGradient}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
              >
                <FontAwesome name="shopping-cart" size={24} color="#fff" />
                {likedDishes.length > 0 && (
                  <View style={styles.badge}>
                    <ThemedText style={styles.badgeText}>
                      {likedDishes.length}
                    </ThemedText>
                  </View>
                )}
              </LinearGradient>
            </TouchableOpacity>

            {/* 购物车抽屉 */}
            <CartDrawer
              isVisible={isCartOpen}
              onClose={() => setIsCartOpen(false)}
              likedDishes={likedDishesData}
              onRemoveDish={handleRemoveDish}
              onConfirm={handleConfirmDishes}
              isConfirming={isConfirming}
            />
          </View>
        </GestureHandlerRootView>
      </LinearGradient>
      <CustomAlert 
        visible={alertConfig.visible}
        message={alertConfig.message}
        type={alertConfig.type}
        onClose={() => setAlertConfig(prev => ({ ...prev, visible: false }))}
      />
      {toastConfig.visible && (
        <Toast
          message={toastConfig.message}
          type={toastConfig.type}
          onHide={() => setToastConfig(prev => ({ ...prev, visible: false }))}
        />
      )}
      <AddDishModal
        visible={isAddDishModalVisible}
        onClose={() => setIsAddDishModalVisible(false)}
        onSuccess={handleAddDishSuccess}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: '#FF9F45',
  },
  gradient: {
    flex: 1,
  },
  container: {
    flex: 1,
    backgroundColor: 'rgba(255,255,255,0.95)',
  },
  mainContent: {
    flex: 1,
  },
  todayDishes: {
    paddingVertical: 15,
    backgroundColor: 'rgba(255,255,255,0.9)',
    borderBottomWidth: 1,
    borderBottomColor: 'rgba(255,159,69,0.1)',
  },
  todayHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 15,
    marginBottom: 10,
  },
  todayTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#FF9F45',
  },
  todayScroll: {
    paddingLeft: 15,
  },
  todayDishItem: {
    marginRight: 15,
    width: 140,
    height: 100,
    position: 'relative',
    borderRadius: 12,
    overflow: 'hidden',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.15,
    shadowRadius: 8,
    elevation: 4,
  },
  todayDishImage: {
    width: '100%',
    height: '100%',
    borderRadius: 12,
  },
  todayDishGradient: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    height: '50%',
    justifyContent: 'flex-end',
    padding: 8,
  },
  todayDishName: {
    color: '#fff',
    fontSize: 14,
    fontWeight: '600',
    textShadowColor: 'rgba(0,0,0,0.3)',
    textShadowOffset: { width: 0, height: 1 },
    textShadowRadius: 2,
  },
  emptyContainer: {
    padding: 30,
    alignItems: 'center',
    justifyContent: 'center',
    gap: 12,
  },
  emptyText: {
    fontSize: 16,
    color: '#FF9F45',
    fontWeight: '500',
  },
  tabContainer: {
    backgroundColor: 'rgba(255,255,255,0.9)',
    borderBottomWidth: 1,
    borderBottomColor: 'rgba(255,159,69,0.1)',
  },
  tabBar: {
    backgroundColor: 'transparent',
    borderWidth: 0,
    elevation: 0,
  },
  indicator: {
    backgroundColor: '#FF9F45',
    height: 3,
    borderRadius: 1.5,
  },
  floatingCart: {
    position: 'absolute',
    right: 20,
    bottom: 20,
    width: 56,
    height: 56,
    borderRadius: 28,
    overflow: 'hidden',
    elevation: 8,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.25,
    shadowRadius: 8,
  },
  cartGradient: {
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  badge: {
    position: 'absolute',
    top: 8,
    right: 8,
    backgroundColor: '#fff',
    borderRadius: 10,
    minWidth: 20,
    height: 20,
    justifyContent: 'center',
    alignItems: 'center',
    borderWidth: 1.5,
    borderColor: '#FF9F45',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.15,
    shadowRadius: 4,
    elevation: 3,
  },
  badgeText: {
    color: '#FF9F45',
    fontSize: 11,
    fontWeight: 'bold',
    marginTop: Platform.OS === 'ios' ? 1 : 0,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
  },
  errorText: {
    color: '#E74C3C',
    fontSize: 16,
    fontWeight: 'bold',
  },
  tabContent: {
    width: '100%',
    height: '100%',
  },
  content: {
    flex: 1,
    backgroundColor: '#FFF8F3',
  },
  dishesContainer: {
    padding: 20,
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
    gap: 15,
  },
  deleteTodayDish: {
    position: 'absolute',
    top: 0,
    right: 0,
    zIndex: 10,
  },
  deleteIconContainer: {
    width: 22,
    height: 22,
    borderRadius: 11,
    backgroundColor: 'white',
    justifyContent: 'center',
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5,
  },
  addButton: {
    overflow: 'hidden',
    borderRadius: 20,
  },
  addButtonGradient: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 8,
    paddingHorizontal: 12,
    gap: 4,
  },
  addButtonText: {
    color: '#fff',
    fontSize: 14,
    fontWeight: '600',
  },
});
